package com.woniuxy.hrms.service.impl;

import com.woniuxy.hrms.dao.AccountDao;
import com.woniuxy.hrms.dao.impl.AccountDaoImpl;
import com.woniuxy.hrms.entity.Account;
import com.woniuxy.hrms.service.AccountService;
import com.woniuxy.hrms.util.DBUtil;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @program: hrms
 * @description:
 * @create: 2024-08-09 15:34
 **/
public class AccountServiceImpl implements AccountService {
    AccountDao accountDao = new AccountDaoImpl();
    @Override
    public boolean transferAccount(String fromAccount, String toAccount, BigDecimal money) throws SQLException {
        Connection con= DBUtil.getCon();
        System.out.println(con.getAutoCommit());
        con.setAutoCommit(false);
        //转账用户操作
        try {
            Account account1 = accountDao.queryByNo(fromAccount);//查询from的账户
            account1.setBalance(account1.getBalance().subtract(money));
            accountDao.update(account1,con);
            //接收用户操作
            Account account2 = accountDao.queryByNo(toAccount);
            account2.setBalance(account2.getBalance().add(money));
            accountDao.update(account2,con);
            con.commit();//提交事务
        } catch (SQLException e) {
            con.rollback();//出现异常，则回滚
        }
        con.close();
        return true;
    }
}
